package test4.noLock;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @author 天启
 * @date 2020-02-19 16:31
 * @description 账户排序
 */
@AllArgsConstructor
@Data
public class AccountWithoutLock {

    private Integer id;
    private String name;
    private int balance;

    /**
     * 转账
     *
     * @param target 目标
     * @param amt    金额
     */
    static void transferTo(AccountWithoutLock from, AccountWithoutLock target, int amt) {
        AccountWithoutLock left = null;
        AccountWithoutLock right = null;
        if (from.getId() > target.getId()) {
            left = target;
            right = from;
        }
        // 锁定序号小的账户
        try {
            System.out.println(left.toString());
            System.out.println(right.toString());

            synchronized (left) {
                // 锁定序号大的账户
                synchronized (right) {
                    if (from.getBalance() > amt) {
                        from.setBalance(from.getBalance() - amt);
                        ;
                        target.setBalance(target.getBalance() + amt);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}